#!/usr/bin/tclsh

lappend auto_path /usr/local/lib/tcllib1.14

proc space20 {w} {
  upvar $w v
  set v [string map {{ } %20} $v]
}

foreach {i j} {
  BAW {British Airways} EIN {Aer Lingus} VIR {Virgin Atlantic} GFA {Gulf Air} UAE Emirates AIC {Air India}
  AFR {Air France} DLH Lufthansa IBE IBERIA ELY {El Al} SHT {British Airways Shuttle} BMA {British Midland}
  TAM {TAM Airlines} EZY easyJet BCY CityJet ANZ {Air Newzealand} QFA Qantas SIA {Singapore Airlines} KAL {Korean Air}
  ACA {Air Canada} CTN {Croatia Airlines} AAL {American Airlines} UAL {United Airlines} COA {Continental Airlines} RYR {Ryanair}
  TOM {Thomson Airways} KLM KLM SAS {Scandinavian Airlines} TCX {Thomas Cook Airlines} DAL {Delta Airlines} IWD {Orbest Airlines}
  AEE {Aegean Airlines} SLM {Surinam Airways} FIN Finnair BMI bmibaby TAP {Air Portugal} GMA {Gama Aviation} MOV {VIM Airlines}
  THY {Turkish Airlines} RZO {SATA International} TSC {Air Transat} SWR Swissair BEL {Brussels Airlines} MAU {Air Marutius}
  OMA {Oman Air} JAT {JAT Airways} KFR {Kingfisher Airlines} JAI {Jet Airways} CKS {Kalitta Air} IRA {Iran Air} EXS Jet2 AMC {Air Malta} MON {Monarch Airlines}
  AEU {Astraeus Airlines} MAS {Malaysian Airlines} AFL Aeroflot AWE {US Airways} SVA {Saudi Arabian Airlines} ALK {Srilankan Airlines} CPA {Cathay Pacific}
  TSO {Transaero Airlines} AZA Alitalia ROT Tarom IB3 Iberia MEA {Middle Eastern Airlines} QTR {Qatar Airways} PIA {Pakistan International}
  ICE {Iceland Air} SAA {South African Airways} ETH Ethiopian ETD {Etihad Airways} CLX CargoLux CCA {Air China} AAR {Asiana Airlines} RBA {Royal Brunei Airlines}
  SEY {Air Seychelles} MSR {Egyptair} THA {Thai Airways} EVA {Eva Air} AUA {Austrian Airlines} NAX {Norweigian Air Shuttle} KAC {Kuwait Airways} CYP {Cyprus Air} TUA {Turkmenistan Airlines}
  SYR {Syrian Airlines} VLG {Vueling Airlines} CAL {China Airlines} TAR {Tunis Air} ANA {All Nippon Airways} KQA {Keynya Airways} LOT {LOT - Polish Airlines}
  WZZ {Wizz Air} DAH {Air Algerie} BBC {Biman Bangladesh} MNG {MNG Cargo} RAM {Royal Air Maroc} JAL {Japan Airlines} RJA {Royal Jordanian Airlines} FDX FedEx ARA {Arik Air}
  ATN {Air Transport International} UA {United Airlines} CES {China Eastern Airlines} UZB {Uzbekistan Airways} AHY {Azerbaijan Airlines} LZB {Bulgaria Air} UPS {United Parcel Services}
  QAF {Qatar Amiri Flight} OAW {Helvetic Airways} VKG {Thomas Cook Airlines} BLX {TUIfly Nordic} PTI {PrivatAir} SBI {S7 Airlines} PGT {Pegasus Airlines} CSA {Czech Airlines}
  CFG {Condor Flugdienst} CSN {China Southern Airlines} NVR Novair GWI Germanwings BCS DHL AMX Mexicana SMX {Alitalia Express} SQC {Singapore Airlines Cargo} BOX Aerologic
  FPO {Europe Airpost} AWC {Titan Airways} MNG {MNG Cargo} TAY {TNT Airways} THT {Air Tahiti Nui} MPH {Martinair Cargo} JAF Jetairfly CSA {Czech Airlines}
} {set airline($i) $j}


set flightnum [lindex $argv 0]
set icao [lindex $argv 1]
set reg [string trim [lindex $argv 2]]
set type [lindex $argv 3]
set itinerary [lindex $argv 4]
set lat [lindex $argv 5]
set lon [lindex $argv 6]
set alt [lindex $argv 7]
set intent [lindex $argv 8]
set heading [lindex $argv 9]
set status [lindex $argv 10]
set speed [lindex $argv 12]

set flight [string range [lindex $argv 0] 0 2]

if { [array names airline -exact $flight] ne "" } {
  set caller $airline($flight)
} else {
  set caller unknown
}


if {$reg eq "------"} {

  load /usr/lib/libtclsqlite3.so
  sqlite3 db planes.db

  set D [db eval [list SELECT * FROM AIRCRAFT WHERE ModeS = '$icao']]
  if {[llength $D]} {
    set reg [lindex $D 5]
    set type [lindex $D 6]
  } else {
    set reghtml [exec curl http://data.flight24.com/_ajaxcalls/autocomplete_airplanes.php?typing=$icao --connect-timeout 10 2> err]
    set regfirst [string first ' $reghtml]
    set regend [string first , $reghtml]
    set reg [string range $reghtml [incr regfirst] [incr regend -1]]
  }

}

foreach i {alt intent} {space20 $i}

set fd [open out w]


  package require json

  #set geocode [exec curl http://nominatim.openstreetmap.org/reverse?format=json&lat=$lat&lon=$lon 2> err]
  set geocode [exec curl http://open.mapquestapi.com/nominatim/v1/reverse?format=json&&lat=$lat&lon=$lon 2> err]

  set D [::json::json2dict $geocode]
  set addr [dict get $D address]

  set keys [dict keys $addr]

  set key0 [lindex $keys 0]

  set loc [dict get $addr $key0]
  if {[string first { } $loc] eq -1} {
    set loc "[string toupper [string map {_ { }} $key0] 0 0] of $loc"
  }

  set county {in this County}
  if {[dict exists $addr county]} {
    set county "in [dict get $addr county]"
    set county [string map {{County Council} {} {Royal Borough of } {}} $county]
  }

  set address "$loc $county"

  space20 address

if {$itinerary eq 1} {


  set html [exec curl http://data.flight24.com/airplanes/$reg/ --connect-timeout 10 2> err]

  set start [string first {CET  from} $html]
  set html [string range $html $start end]

  foreach i {from to} {

    set needle title="
    set len [string length $needle]

    set start [string first $needle $html]
    incr start $len

    set html [string range $html $start end]

    set code_start [string first > $html]
    set code_end [string first < $html]
    set code [string trimleft [string range $html [incr code_start] [incr code_end -1]]]
    set [set i]_iata $code

    set wiki [exec curl http://en.wikipedia.org/wiki/List_of_airports_by_IATA_code:_[string index $code 0] --connect-timeout 20 2> err]
    set start [string first >$code $wiki]
    set wiki [string range $wiki $start end]

    set needle /wiki/
    set len [string length $needle]

    set start [string first $needle $wiki]
    incr start $len

    set wiki [string range $wiki $start end]
    set end [string first {"} $wiki]
    incr end -1

    set airport_name [string trim [string range $wiki 0 $end]]
    set airport_name [string map {\" '} $airport_name]
    set [set i]_link $airport_name


    set airport_name [string map {_ { } Airport {}} $airport_name]

    set $i $airport_name
    #puts "$flightnum [set $i]"

  }

  puts $fd $caller
  close $fd

  source twitter.tcl

  space20 from
  space20 to
  space20 caller
  space20 from_link
  space20 to_link

  set poster1 "http://atc.manurevah.com/flight_post.php?icao=$icao&flight=$flightnum&regn=$reg&from_iata=$from_iata&to_iata=$to_iata&from=$from&to=$to&type=$type&airline=$caller&alt=$alt&intent=$intent&status=$status&lat=$lat&lon=$lon&hdg=$heading&speed=$speed&from_link=$from_link&to_link=$to_link&address=$address"
  set poster2 "http://jagernot.com/lhr/flight_post.php?icao=$icao&flight=$flightnum&regn=$reg&from_iata=$from_iata&to_iata=$to_iata&from=$from&to=$to&type=$type&airline=$caller&alt=$alt&intent=$intent&status=$status&lat=$lat&lon=$lon&hdg=$heading&speed=$speed&link1=$from_link&link2=$to_link&address=$address"

} else {
  set poster1 "http://atc.manurevah.com/flight_post.php?&icao=$icao&alt=$alt&intent=$intent&status=$status&lat=$lat&lon=$lon&hdg=$heading&speed=$speed&address=$address"
  set poster2 "http://jagernot.com/lhr/flight_post.php?&icao=$icao&alt=$alt&intent=$intent&status=$status&lat=$lat&lon=$lon&hdg=$heading&speed=$speed&address=$address"

}

exec curl $poster1 >& err &
exec curl $poster2 >& err &
